import moment from "moment"
export const getEnv = () => {
  if ("localhost".indexOf(location.hostname) >= 0) {
    return "dev"
  }
  return "prod"
}
// 中、英日期转换
export const formatDate = (date) => {
  if (!date) return ""
  moment.locale("en")
  const arr = date.substr(0, 10).split("-")
  const month = moment(arr[1]).format("MMMM")
  return `${month} ${arr[2]},${arr[0]}`
}

// 获取指定sessionStorage数据
export const getSesstionStorage = function (key) {
  if (!key) return null
  return sessionStorage.getItem(key) ? JSON.parse(sessionStorage.getItem(key)) : null
}
// 保存指定sessionStorage数据
export const setSesstionStorage = function (key, data) {
  if (!data) return
  sessionStorage.setItem(key, JSON.stringify(data))
}
//获取地址栏参数，用于问号型传参
export const urlParam = (paramName) => {
  const paramArray = window.location.href.match(/([^?=&]+)(=([^&]*))/g) || []
  const reducer = (accumulator, currentValue) => {
    const arr = currentValue.split("=") || []
    accumulator[arr[0]] = arr[1]

    return accumulator
  }
  const result = paramArray.reduce(reducer, {})

  return paramName ? result[paramName] : result
}
// 复制链接
export const copyUrl = function (url) {
  if (!url) return
  const el = document.createElement("textarea")
  el.value = url
  document.body.appendChild(el)
  el.select()
  document.execCommand("copy")
  document.body.removeChild(el)
}
// 从数组中获取指定obj
export const getArrayObjectByProp = (arr, prop, val) => {
  if (!Array.isArray(arr)) return null
  let obj = null
  arr.map((item) => {
    if (item[prop] == val) obj = item
  })
  return obj
}
// 从数组中获取指定obj所处下标
export const getArrayIndexByProp = (arr, prop, val) => {
  if (!Array.isArray(arr)) return -1
  let _index = -1
  arr.map((item, index) => {
    if (item[prop] == val) {
      _index = index
    }
  })
  return _index
}

export function wait(time = rnd(500, 1000, Math.round)) {
  return new Promise((resolve) => setTimeout(resolve, time))
}

export function rnd(min = 0, max = 1, format = (value) => value) {
  let num = Math.random()
  num = num * (max - min)
  num = min + num
  num = format(num)
  return num
}

// 获取对象类型
export function typeOf(object) {
  return {}.toString.call(object).slice(8, -1)
}

// 是js基础对象
export function isObject(object) {
  return typeOf(object) === "Object"
}

// 判断对象是否有某个key, 例：
// hasProp({name: null}, 'name') >> true
// hasProp({name: null}, 'value') >> false
// hasProp([], 'length') >> true
// hasProp([null], '0') >> true
export function hasProp(object, prop) {
  return {}.hasOwnProperty.call(object, prop)
}

// url参数字符串 >> 对象
export function qsParse(string) {
  return Object.fromEntries(new URLSearchParams(string).entries())
}

// 对象 >> url参数字符串
export function qsString(object) {
  return new URLSearchParams(object) + ""
}

// url拼接，支持对象拼接成参数
export function pathJoin(...pathSeq) {
  let url = "."
  let query = {}
  // 没有用的路径片段
  let isNone = (path) => !path || ["./", "."].includes(path)

  // 路径格式修正
  let urlize = (string) => {
    // 如果是相对路径 要补齐前面的 `./`
    if (!string.startsWith("/") && !string.startsWith("./") && !string.startsWith("../")) string = "./" + string
    // 去除重复的斜杠
    string = string.replace(/\/{2,}/g, "/")
    return string
  }

  for (let fragment of pathSeq) {
    if (isObject(fragment)) {
      Object.assign(query, fragment)
      continue
    }
    let [path, search] = fragment.split("?")
    if (search) Object.assign(query, qsParse(search))

    // 无效path不操作
    if (isNone(path)) continue

    // 如果是有效path, url路径中最后一段不带斜杠需要被忽略
    if (!url.endsWith("/")) url = url.replace(/[^/]+$/, "")

    url = urlize(url)

    if (path.startsWith("/") || isNone(url)) {
      url = path
      continue
    }

    // 上级路径
    while (path.startsWith("../")) {
      path = path.replace(/^\.\.\//, "")
      if (/\/[^/]+\/$/.test(url)) {
        url = url.replace(/\/[^/]+\/$/, "/")
      }
    }

    if (path.startsWith("./")) path = path.replace(/^\.\//, "")
    url += path
  }
  url = urlize(url)

  return url
}
